package com.woniu.zsd.gateway.exception;

import cn.hutool.json.JSONUtil;
import com.woniu.zsd.common.util.Result;
import org.springframework.boot.web.reactive.error.ErrorWebExceptionHandler;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Component
public class GatewayGlobalExceptionHandler implements ErrorWebExceptionHandler {
    @Override
    public Mono<Void> handle(ServerWebExchange exchange, Throwable throwable) {
        exchange.getResponse().getHeaders().setContentType(MediaType.APPLICATION_JSON);
        return exchange.getResponse().writeWith(Mono.fromSupplier(() -> {
            Result<Object> result = new Result<>();
            result.setCode(500);
            result.setMessage(throwable.getMessage());
            String jsonStr = JSONUtil.toJsonStr(result);
            return exchange.getResponse().bufferFactory().wrap(jsonStr.getBytes());
        }));
    }
}
